const Koa = require('koa');
const Router = require('@koa/router');
const KoaBody = require('koa-body');
const fs = require('fs');
const path = require('path');
const send = require('koa-send');

const app = new Koa();
const router = new Router();

async function delay(time = 1000) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve();
    }, time);
  });
}

app.use(KoaBody({
  multipart: true, // 支持文件上传
  formidable: {
    maxFieldsSize: 2 * 1024 * 1024 // 文件上传大小,
  }
}));

router.get('/testGet', async(ctx, next) => {
  const { name = 'default', age = 18 } = ctx.request.query;
  await delay(1000);
  ctx.body = {
    code: 200,
    data: {
      content: `姓名: ${name}, 年龄: ${age}`
    },
    msg: ''
  };
});

router.get('/get/:name/:age', (ctx, next) => {
  const { name = 'default', age = 18 } = ctx.params;
  ctx.body = {
    code: 200,
    data: {
      content: `姓名: ${name}, 年龄: ${age}`
    },
    msg: ''
  };
});

router.post('/post', (ctx, next) => {
  const { name = 'default', age = 18 } = ctx.request.body;
  ctx.body = {
    code: 200,
    data: {
      content: `姓名: ${name}, 年龄: ${age}`
    },
    msg: ''
  };
});

router.post('/upload', (ctx, next) => {
  const file = ctx.request.files.file;
  // 创建可读流
  const reader = fs.createReadStream(file.path);
  const filePath = path.join(__dirname, 'public/upload/') + `/${file.name}`;
  // 创建可写流
  const upStream = fs.createWriteStream(filePath);
  // 可读流通过管道写入可写流
  reader.pipe(upStream);
  ctx.body = {
    code: 200,
    data: '上传成功！',
    msg: ''
  };
});

router.get('/download', async(ctx, next) => {
  const path = `public/upload/4.jpg`;
  ctx.attachment(path);
  await send(ctx, path);
});

router.get('/401', async(ctx, next) => {
  ctx.body = {
    code: 401,
    data: null,
    msg: '无权限!'
  };
});

app.use(router.routes());

app.listen(3000, () => {
  console.log('启动成功,http://localhost:3000');
});
